const _ = require('lodash')
const ResponseError = require('../helper/ResponseError')

const validateRequest = (validations = []) => (req, res, next) => {
  try {
    const errors = validations.reduce((previousResult, validation) => {
      const { field, required, format } = validation
      const value = _.get(req, field)
      const fieldName = field.split('.').slice(-1)[0]
      // console.log('fieldName', fieldName, 'required', required, 'value', value)
      const requiredValue = _.isFunction(required) ? required(req) : !!required
      if (requiredValue && typeof value === 'undefined') {
        const error = new ResponseError.ParameterRequired()
        error.field = fieldName
        return [...previousResult, error]
      }
      if (typeof value !== 'undefined' && !format(value)) {
        const error = new ResponseError.ValidationError()
        error.field = fieldName
        return [...previousResult, error]
      }
      return previousResult
    }, [])
    if (errors.length > 0) {
      return next(errors)
    }
  } catch (error) {
    return next(error)
  }
  return next()
}

module.exports = validateRequest
